import axios from "axios";
import {ElMessage} from "element-plus";

const defaultError = ()=> {
    ElMessage.error("发生了一些错误，请联系管理员")
}
const defaultFailure = (message)=> {
    ElMessage.warning(message)
}

function post(url, data, success, failure=defaultFailure, error=defaultError) {
    axios.post(url, data, {
        headers: {
            'Content-type': 'application/json;charset=UTF-8'
        },
        // 带上cookie
        withCredentials: true
        // 从返回的响应对象解构出 data
    }).then(({data})=> {
        console.log(data)
        if (data.status === 200) {
            if (data.data === null) {
                success(data.msg)
            } else {
                success(data.data, data.msg)
            }
        } else {
            failure(data.msg)
        }
    }).catch(error)
}
function postForm(url, data, success, failure=defaultFailure, error=defaultError) {
    axios.post(url, data, {
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        },
        // 带上cookie
        withCredentials: true
        // 从返回的响应对象解构出 data
    }).then(({data})=> {
        console.log(data)
        if (data.status === 200) {
            if (data.data === null) {
                success(data.msg)
            } else {
                success(data.data, data.msg)
            }
        } else {
            failure(data.msg)
        }
    }).catch(error)
}
function get(url, success, failure=defaultFailure, error=defaultError) {
    axios.get(url, {
        // 带上cookie
        withCredentials: true
    }).then(({data})=> {
        console.log(data)
        if (data.status === 200 || Array.isArray(data)) {
            if (Array.isArray(data)) {
                success(data)
            }
            success(data.data, data.msg)
        } else {
            failure(data.msg, data.status)
        }
    }).catch(error)
}

function put(url, data, success, failure = defaultFailure, error = defaultError) {
    axios.put(url, data, {
        headers: {
            'Content-type': 'application/json;charset=UTF-8'
        },
        withCredentials: true
    }).then(({ data }) => {
        console.log(data)
        if (data.status === 200) {
            success(data.msg, data.status)
        } else {
            failure(data.msg, data.status)
        }
    }).catch(error)
}

function myDelete(url, success, failure = defaultFailure, error = defaultError) {
    axios.delete(url, {
        withCredentials: true
    }).then(({ data }) => {
        console.log(data)
        if (data.status === 200) {
            success(data.msg, data.status)
        } else {
            failure(data.msg, data.status)
        }
    }).catch(error)
}
export {get, post, put, myDelete, postForm}